package com.example.mylibrary.util;

import android.content.Context;
import android.os.Environment;
import android.os.Process;
import android.util.Log;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.PrintWriter;
import java.lang.Thread.UncaughtExceptionHandler;
import java.text.SimpleDateFormat;
import java.util.Date;

public class CrashHandler implements UncaughtExceptionHandler {
	private static final String TAG = "CrashHandler";
	private static boolean DEBUG = true;
	private static final String PATH = Environment
			.getExternalStorageDirectory().getPath() + "/人证核验系统数据库/crashLog/";
	private static final String FILE_NAME = "crash";
	private static final String FILE_NAME_SUFFIX = ".txt";
	private static CrashHandler sInstance = new CrashHandler();
	private UncaughtExceptionHandler uncaughtExceptionHandler;
	private Context context;

	public static CrashHandler getInstance() {
		return sInstance;
	}

	public void init(Context context) {
		uncaughtExceptionHandler = Thread.getDefaultUncaughtExceptionHandler();
		Thread.setDefaultUncaughtExceptionHandler(this);
		this.context = context.getApplicationContext();
	}

	@Override
	public void uncaughtException(Thread thread, Throwable ex) {
		dumpExceptionToLocation(ex);
		ex.printStackTrace();
		if (uncaughtExceptionHandler != null) {
			uncaughtExceptionHandler.uncaughtException(thread, ex);
		}else{
			Process.killProcess(Process.myPid());
		}
	}

	private void dumpExceptionToLocation(Throwable ex) {
		if (!Environment.getExternalStorageState().equals(
				Environment.MEDIA_MOUNTED)) {
			if (DEBUG) {
				Log.e(TAG, "sdcard unmounted,skip dump exception");
				return;
			}
		}
		File dir = new File(PATH);
		if (!dir.exists())
			dir.mkdirs();
		String time = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
				.format(new Date(System.currentTimeMillis()));
		File file = new File(dir, FILE_NAME + time + FILE_NAME_SUFFIX);
		try {
			PrintWriter pw = new PrintWriter(new BufferedWriter(new FileWriter(
					file)));
			pw.println(time);
			pw.println();
			ex.printStackTrace(pw);
			pw.close();
		} catch (Exception e) {
			Log.e(TAG, "dump crash info fail");
		}
	}


}
